package com.example.interceptors;

import com.example.annotation.PassToken;
import com.example.common.Constants;
import com.example.common.exception.BusinessException;
import com.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * Create By ChenXiAoBin
 * on 2019/1/21
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    /**
     * 进入controller层之前拦截请求
     * @param httpServletRequest
     * @param httpServletResponse
     * @param object
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {


        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        //LOG.info("---------------------开始进入请求地址拦截----------------------------");
        String f = httpServletRequest.getHeader("Authorization");
        String userId = RedisUtil.get(f);
        if(!httpServletRequest.getMethod().equals("OPTIONS")){
            if(userId != null && !"".equals(userId)){
                return true;
            }else {
                throw new BusinessException(1,"请登录");
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //LOG.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       // LOG.info("---------------视图渲染之后的操作-------------------------0");
    }


}
